package com.core.reach.cloudhub.service.impl;

import com.core.reach.cloudhub.dao.OrderMapper;
import com.core.reach.cloudhub.domain.Order;
import com.core.reach.cloudhub.service.AccountService;
import com.core.reach.cloudhub.service.OrderService;
import com.core.reach.cloudhub.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author ga.zhang
 * @version V1.0
 * @description: TODO
 * @date 2020/4/1 9:50
 **/
@Slf4j
@Service("orderService")
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private StorageService storageService;

    @Resource
    private AccountService accountService;

    @Override
    @GlobalTransactional(name = "test_rollback", rollbackFor = Exception.class)
    public Boolean createOrder(Order order) {
        log.info("*************************下单开始*************************");

        log.info("step 1------------->开始创建订单");
        Integer step1 = orderMapper.createOrder(order);
        log.info("step 1------------->创建订单完成");

        log.info("step 2------------->调库存微服务，开始库存扣减");
        storageService.decrease(order.getProductId(), order.getCount());
        log.info("step 2------------->调库存微服务，库存扣减完成");

        log.info("step 3------------->调账户微服务，开始余额扣减");
        accountService.decrease(order.getUserId(), order.getMoney());
        log.info("step 3------------->调账户微服务，余额扣减完成");

        log.info("step 4------------->开始修改订单状态");
        Integer step4 = orderMapper.updateOrder(order.getUserId(), 0);
        log.info("step 4------------->订单状态修改完成");

        log.info("*************************下单完成*************************");
        return step1 > 0 && step4 > 0;
    }
}
